/*DONE* Object:  Table [dbo].[<CompanyName>$Purchase Line Archive$5ecfc871-5d82-43f1-9c54-59685e82318d] 2/2  Script Date: 06.05.2022 - GKO ******/
/*Add prestaging tables for all companies in LSInsight$Companies table*/

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

DECLARE @CreateTable as VARCHAR(MAX)
DECLARE @Company as VARCHAR(100)
DECLARE @CompanyCounter as INT
DECLARE @i as INT

SET @i = 0
SET @CompanyCounter = (SELECT MAX([Company]) FROM LSInsight$Companies)

WHILE @i <= @CompanyCounter 
BEGIN
SET @Company = (SELECT LSInsight$Companies.[CompanyPrefix] from dbo.LSInsight$Companies WHERE [Company] = @i)

IF @Company IS NOT NULL
BEGIN

DECLARE @DropTable as VARCHAR(MAX)
SET @DropTable = 'DROP TABLE IF EXISTS [dbo].['+@Company+'$Purchase Line Archive$5ecfc871-5d82-43f1-9c54-59685e82318d]'
EXEC(@DropTable)

SET @CreateTable =
'CREATE TABLE [dbo].['+@Company+'$Purchase Line Archive$5ecfc871-5d82-43f1-9c54-59685e82318d](
	[timestamp] [timestamp] NOT NULL,
	[Document Type] [int] NOT NULL,
	[Document No_] [nvarchar](20) NOT NULL,
	[Doc_ No_ Occurrence] [int] NOT NULL,
	[Version No_] [int] NOT NULL,
	[Line No_] [int] NOT NULL,
	[LSC Retail Product Code] [nvarchar](20) NOT NULL,
	 CONSTRAINT ['+@Company+'$Purchase Line Archive$5ecfc871-5d82-43f1-9c54-59685e82318d$Key1] PRIMARY KEY CLUSTERED 
(
	[Document Type] ASC,
	[Document No_] ASC,
	[Doc_ No_ Occurrence] ASC,
	[Version No_] ASC,
	[Line No_] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]'

EXEC(@CreateTable)

END
SET @i = @i+1
END
